/*
 * CommandLoop.c
 *
 *  Created on: 2014-3-18
 *      Author: Rome
 */

#include "commandloop.h"
#include "string.h"
#include "at24c16.h"
#include "unistd.h"

alt_32 DecodeRevBuf(alt_u8* RecvBuf, alt_u8* SendBuf, alt_u32 Length)
{
	alt_u8* local_RecvBuf = RecvBuf;
	alt_u8* local_SendBuf = SendBuf;
	alt_u8 OP, WriteReq;
	alt_32 ReturnValue;

	alt_u32 op_addr, op_legnth;

	int i;
	// initial send buffer to error
	if(Length > 128)
		return -1;
	for(i = 0; i < Length; i ++)
		*(SendBuf + i) = 0xFF;

	// check sof
	if(*local_RecvBuf != COMMAND_SOF_0)
		return -1;
	local_RecvBuf ++;
	if(*local_RecvBuf != COMMAND_SOF_1)
		return -1;
	local_RecvBuf ++;
	if(*local_RecvBuf != COMMAND_SOF_2)
		return -1;
	local_RecvBuf ++;
	if(*local_RecvBuf != COMMAND_SOF_3)
		return -1;

	// prepare send buffer
	memcpy(local_SendBuf, RecvBuf, 14);

	// check operation target
	local_RecvBuf ++;
	OP = *local_RecvBuf;
	// check read or write
	local_RecvBuf ++;
	WriteReq = *local_RecvBuf;

	// check address
	local_RecvBuf ++;
	op_addr = (*(local_RecvBuf)) << 24;
	local_RecvBuf ++;
	op_addr += (*(local_RecvBuf)) << 16;
	local_RecvBuf ++;
	op_addr += (*(local_RecvBuf)) << 8;
	local_RecvBuf ++;
	op_addr += (*(local_RecvBuf));

	// check length
	local_RecvBuf ++;
	op_legnth = (*(local_RecvBuf)) << 24;
	local_RecvBuf ++;
	op_legnth += (*(local_RecvBuf)) << 16;
	local_RecvBuf ++;
	op_legnth += (*(local_RecvBuf)) << 8;
	local_RecvBuf ++;
	op_legnth += (*(local_RecvBuf));

	local_RecvBuf ++;
	local_SendBuf = local_SendBuf + 14;
	switch(OP)
	{
	case OP_TARGET_EEPROM:
		{

			if(WriteReq != 0)
			{
				At24c16Write((alt_u16 )op_addr, local_RecvBuf, (alt_u16)op_legnth);
//				AT24C16_W((unsigned short)(op_addr + i), *(local_RecvBuf + i));
			}
//				usleep(400);
//			*local_SendBuf = AT24C16_R((unsigned short)(op_addr + i));
//			local_SendBuf ++;
			At24c16Read((alt_u16)op_addr, local_SendBuf, (alt_u16)op_legnth);

			break;
		}
	case OP_TARGET_IIC:
		break;
	case OP_TARGET_RS485A:
		break;
	case OP_TARGET_RS485B:
		break;
	default:
		break;
	}
	ReturnValue = op_legnth + 14;	// add sof length
	return ReturnValue;
}
